package com.molichuxing.gateway.bff.stock.services.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import com.molichuxing.services.infrastructure.dto.request.create.FenceCreateDto;
import com.molichuxing.services.infrastructure.service.FenceStoreStockService;
import com.molichuxing.services.property.FenceStoreStockTypeEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.molichuxing.framework.dto.Paged;
import com.molichuxing.framework.exception.BizException;
import com.molichuxing.framework.utils.DateTypeUtil;
import com.molichuxing.framework.utils.ObjectCastUtil;
import com.molichuxing.gateway.bff.stock.convertor.Convert;
import com.molichuxing.gateway.bff.stock.entity.request.create.EntrepotStorageCreateVo;
import com.molichuxing.gateway.bff.stock.entity.request.modify.EntrepotStorageModifyVo;
import com.molichuxing.gateway.bff.stock.entity.response.EntrepotStorageBaseVo;
import com.molichuxing.gateway.bff.stock.entity.response.EntrepotStorageVo;
import com.molichuxing.gateway.bff.stock.entity.response.FenceBaseVo;
import com.molichuxing.gateway.bff.stock.services.EntrepotStorageBffService;
import com.molichuxing.services.business.dto.request.create.EntrepotStorageBizCreateDto;
import com.molichuxing.services.business.dto.request.modify.EntrepotStorageBizModifyDto;
import com.molichuxing.services.business.dto.response.EntrepotStorageBizDto;
import com.molichuxing.services.business.dto.response.StoreBizDto;
import com.molichuxing.services.business.service.EntrepotStorageBizService;
import com.molichuxing.services.business.service.StoreBizService;
import com.molichuxing.services.infrastructure.dto.request.create.IovFenceCreateDto;
import com.molichuxing.services.infrastructure.dto.request.modify.IovFenceModifyDto;
import com.molichuxing.services.infrastructure.dto.response.EntrepotStorageDto;
import com.molichuxing.services.infrastructure.dto.response.IovFenceDto;
import com.molichuxing.services.infrastructure.dto.response.RegionInfoDto;
import com.molichuxing.services.infrastructure.service.EntrepotStorageService;
import com.molichuxing.services.infrastructure.service.IovFenceService;
import com.molichuxing.services.infrastructure.service.RegionService;
import com.molichuxing.services.property.IovFenceAlarmTypeEnum;
import com.molichuxing.services.property.IovFenceShapeEnum;
import com.molichuxing.services.property.StockCarStockTypeEnum;

/**
 * 
 * @author liyg
 * 中转库bff服务实现类
 * 2019-08-26
 *
 */
@Service("entrepotStorageBffService")
public class EntrepotStorageBffServiceImpl implements EntrepotStorageBffService{
	
	private static final Logger logger = LoggerFactory.getLogger(EntrepotStorageBffServiceImpl.class);
	
	@Value("${store.fence.width}")
    private String STORE_FENCE_WIDTH;

	@Resource
	private EntrepotStorageBizService entrepotStorageBizService;
	
	@Resource
	private EntrepotStorageService entrepotStorageService;
	
	@Resource
	private IovFenceService iovFenceService;
	
	@Resource
	private RegionService regionService;
	
	@Resource
	private StoreBizService storeBizService;

	@Resource
	private FenceStoreStockService fenceStoreStockService;
	
	
	/**
	 *获取中转库列表
	 * @param map 参数
	 *key:shortName  String 中转库简称 非必填
	 *key:name       String 负责人姓名 非必填
	 *key:regionId   Integer 城市id 非必填
	 *key:sortName   String 排序字段 
	 *key:sortWay    String 排序方式 
	 *key:pageNum    Integer 当前页
	 *key:pageSize   Integer 每页显示条数
	 * @return
	 */
	@Override
	public Paged<EntrepotStorageVo> getEntrepotStorageList(Map<String, Object> map) {
		
		Paged<EntrepotStorageBizDto> entrepotStoragePaged = entrepotStorageBizService.getEntrepotStorageList(map);
		if(null == entrepotStoragePaged) {
			return new Paged<EntrepotStorageVo>();
		}else if(entrepotStoragePaged.isEmpty()) {
			return new Paged<EntrepotStorageVo>(null,entrepotStoragePaged.getTotal(),entrepotStoragePaged.getPageSize());
		}
		
		List<EntrepotStorageVo> entrepotStorageVoList = Convert.toEntrepotStorageVo(entrepotStoragePaged.getList());
		List<Integer> storageIdList=new ArrayList<>();
		for (EntrepotStorageVo vo : entrepotStorageVoList) {
			RegionInfoDto city = regionService.getCityNameByCityId(vo.getRegionId());
			if(null != city) {
				vo.setProvinceName(city.getProvinceFullName());
				vo.setCityName(city.getCityFullName());		
			}

			storageIdList.add(vo.getStorageId());
		}

        Map<Integer, Integer> fenceCountMap = fenceStoreStockService.getFenceCount(storageIdList, FenceStoreStockTypeEnum.ENTREPOT_STORAGE.getValue());
        for (EntrepotStorageVo vo : entrepotStorageVoList) {
            if(fenceCountMap !=null && fenceCountMap.size() > 0){
                Integer fenceCount = fenceCountMap.get(vo.getStorageId());
                if (null == fenceCount) {
                    fenceCount = 0;
                }
                vo.setFenceCount(fenceCount);
            }else{
                vo.setFenceCount(0);
            }
        }

		long total = entrepotStoragePaged.getTotal();
		int pageSize = entrepotStoragePaged.getPageSize();
		Paged<EntrepotStorageVo> paged=new Paged<>(entrepotStorageVoList,total,pageSize);
		
		return paged;
	}
	
	/**
	 * 获取中转库详情
	 * 
	 * @param id 中转库id
	 * @return
	 */
	@Override
	public EntrepotStorageVo getEntrepotStorage(Integer id) {
		
		EntrepotStorageBizDto entrepotStorage = entrepotStorageBizService.getEntrepotStorage(id);
		EntrepotStorageVo entrepotStorageVo = Convert.toEntrepotStorageVo(entrepotStorage);
		if(null == entrepotStorageVo) {
			return entrepotStorageVo;
		}
		
		RegionInfoDto city = regionService.getCityNameByCityId(entrepotStorageVo.getRegionId());
		if(null != city) {
			entrepotStorageVo.setProvinceId(city.getProvinceId());
			entrepotStorageVo.setProvinceName(city.getProvinceFullName());
			entrepotStorageVo.setCityName(city.getCityFullName());		
		}
		
		return entrepotStorageVo;
	}
	
	/**
	 * 保存中转库信息
	 * 
	 * @param createVo
	 * @return
	 */
	@Override
	public Boolean create(EntrepotStorageCreateVo createVo) {
		
		EntrepotStorageBizCreateDto createDto=new EntrepotStorageBizCreateDto();
		BeanUtils.copyProperties(createVo, createDto);
		
		EntrepotStorageDto entrepotStorageDto = entrepotStorageService.getByName(createDto.getShortName());
		if(null != entrepotStorageDto) {
			throw new BizException(104, "已存在该名称");
		}
		EntrepotStorageDto entrepotStorageDtoFull = entrepotStorageService.getByFullName(createDto.getFullName());
		if(null != entrepotStorageDtoFull) {
			throw new BizException(104, "已存在该名称");
		}
		Integer fenceId = saveIov(createDto);
		if(null == fenceId) {
			throw new BizException(104, "创建围栏失败");
		}

		createDto.setFenceShape(IovFenceShapeEnum.CIRCLE.getValue());
		createDto.setFenceWidth(new BigDecimal(STORE_FENCE_WIDTH));
		createDto.setFenceId(fenceId);
        Integer storageId = entrepotStorageBizService.create(createDto);
        return bingingFence(storageId,fenceId);
	}

	/**
	 * 绑定围栏
	 *
	 * @param storeId
	 * @param fenceId
	 * @return
	 * @throws Exception
	 */
	private Boolean bingingFence(Integer storeId, Integer fenceId) {
		List<Integer> fenceIdList = new ArrayList<>();
		fenceIdList.add(fenceId);

		FenceCreateDto fenceCreateDto = new FenceCreateDto();
		fenceCreateDto.setStoreId(storeId);
		fenceCreateDto.setType(FenceStoreStockTypeEnum.ENTREPOT_STORAGE.getValue());
		fenceCreateDto.setFenceIdList(fenceIdList);
        try {
            return fenceStoreStockService.createFence(fenceCreateDto);
        } catch (Exception e) {
            throw new BizException(104, "绑定围栏失败");
        }
    }

	/**
	 * 修改中转库信息
	 * 
	 * @param modifyVo
	 * @return
	 */
	@Override
	public Boolean modify(EntrepotStorageModifyVo modifyVo) {
		
		EntrepotStorageDto entrepotStorage = entrepotStorageService.getEntrepotStorage(modifyVo.getStorageId());
		if(null == entrepotStorage) {
			throw new BizException(104, "不存在该条信息");
		}
		
		EntrepotStorageDto entrepotStorageDto = entrepotStorageService.getByName(modifyVo.getShortName());
		if(null != entrepotStorageDto) {
			if(!entrepotStorageDto.getId().equals(entrepotStorage.getId())) {
				throw new BizException(104, "已存在该名称");
			}
		}
		EntrepotStorageDto entrepotStorageDtoFull = entrepotStorageService.getByFullName(modifyVo.getFullName());
		if(null != entrepotStorageDtoFull) {
			if(!entrepotStorageDtoFull.getId().equals(entrepotStorage.getId())) {
				throw new BizException(104, "已存在该名称");
			}
		}
		
		
		EntrepotStorageBizModifyDto modifyDto=new EntrepotStorageBizModifyDto();
		BeanUtils.copyProperties(modifyVo, modifyDto);
		modifyDto.setId(modifyVo.getStorageId());
		modifyDto.setShortName(entrepotStorage.getShortName());
		modifyDto.setFullName(entrepotStorage.getFullName());
		Boolean flag = modifyIov(modifyDto,entrepotStorage.getFenceId());
		if(!flag) {
			throw new BizException(104, "修改围栏失败");
		}
		return entrepotStorageBizService.modify(modifyDto);
	}

	/**
	 * 添加围栏
	 * @param createVo
	 * @return
	 */
	private Integer saveIov(EntrepotStorageBizCreateDto createDto) {
		    IovFenceCreateDto iovFenceCreateDto = new IovFenceCreateDto();
	        iovFenceCreateDto.setFenceName(createDto.getShortName());
	        String address=getCityName(createDto.getRegionId())+createDto.getAddress();
	        iovFenceCreateDto.setFenceArea(address);
	        iovFenceCreateDto.setAlarmType(IovFenceAlarmTypeEnum.OUT.getValue());
	        iovFenceCreateDto.setFenceShape(IovFenceShapeEnum.CIRCLE.getValue());
	        iovFenceCreateDto.setRadius(DateTypeUtil.strCastDouble(STORE_FENCE_WIDTH));
	        iovFenceCreateDto.setLatitude(DateTypeUtil.strCastDouble(createDto.getDimension()));
	        iovFenceCreateDto.setLongitude(DateTypeUtil.strCastDouble(createDto.getLongitude()));
	        Integer fenceId = null;
	         try {
	        	 fenceId = iovFenceService.addFence(iovFenceCreateDto);
			} catch (Exception e) {
				logger.error("车联网添加围栏接口异常：",e);
			}
	        return fenceId;
	}
	
	/**
	 * 修改围栏
	 * @param modifyDto
	 * @return
	 */
	private Boolean modifyIov(EntrepotStorageBizModifyDto modifyDto,Integer fenceId) {
		    IovFenceModifyDto iovFenceDto = new IovFenceModifyDto();
		    iovFenceDto.setId(DateTypeUtil.integerCastLong(fenceId));
		    iovFenceDto.setFenceName(modifyDto.getShortName());
		    String address=getCityName(modifyDto.getRegionId())+modifyDto.getAddress();
		    iovFenceDto.setFenceArea(address);
		    iovFenceDto.setAlarmType(IovFenceAlarmTypeEnum.OUT.getValue());
		    iovFenceDto.setFenceShape(IovFenceShapeEnum.CIRCLE.getValue());
		    iovFenceDto.setRadius(DateTypeUtil.strCastDouble(STORE_FENCE_WIDTH));
		    iovFenceDto.setLatitude(DateTypeUtil.strCastDouble(modifyDto.getDimension()));
		    iovFenceDto.setLongitude(DateTypeUtil.strCastDouble(modifyDto.getLongitude()));
	         try {
	        	 return iovFenceService.modifyFence(iovFenceDto);
			} catch (Exception e) {
				logger.error("车联网修改围栏接口异常：",e);
				 return false;
			}
	       
	}
	
	/**
	 * 获取城市名称
	 * @param cityId
	 * @return
	 */
	private String getCityName(Integer cityId) {
		RegionInfoDto city = regionService.getCityNameByCityId(cityId);
		if(null == city) {
			throw new BizException(104, "不存在该城市信息");
		}
		return city.getProvinceFullName()+city.getCityFullName();
	}
	
	/**
	 * 获取中转库列表
	 * @return
	 */
	@Override
	public List<EntrepotStorageVo> getEntrepotStorageList() {
		List<EntrepotStorageDto> entrepotStorageList = entrepotStorageService.getEntrepotStorageList();
		List<EntrepotStorageVo> entrepotStorageVoList= Convert.toEntrepotStorageVoBase(entrepotStorageList);
		
		return entrepotStorageVoList;
	}
	
	/**
	 * 获取中转库列表
	 * @return
	 */
	@Override
	public List<EntrepotStorageVo> getEntrepotStorageLists() {
		Map<String,Object> map = new HashMap<>();
		map.put("pageSize", 1000);
		map.put("pageNum", 1);
		Paged<EntrepotStorageBizDto> entrepotStoragePaged = entrepotStorageBizService.getEntrepotStorageList(map);
		if(null == entrepotStoragePaged) {
			return null;
		}else if(entrepotStoragePaged.isEmpty()) {
			return null;
		}
		List<EntrepotStorageBizDto> list = entrepotStoragePaged.getList();
//		for (EntrepotStorageBizDto vo : list) {
//			IovFenceCreateDto iovFenceCreateDto = new IovFenceCreateDto();
//	        iovFenceCreateDto.setFenceName(vo.getShortName());
//	        String address=getCityName(vo.getRegionId())+vo.getAddress();
//	        iovFenceCreateDto.setFenceArea(address);
//	        iovFenceCreateDto.setAlarmType(IovFenceAlarmTypeEnum.OUT.getValue());
//	        iovFenceCreateDto.setFenceShape(IovFenceShapeEnum.CIRCLE.getValue());
//	        iovFenceCreateDto.setRadius(DateTypeUtil.strCastDouble(STORE_FENCE_WIDTH));
//	        iovFenceCreateDto.setLatitude(DateTypeUtil.strCastDouble(vo.getDimension()));
//	        iovFenceCreateDto.setLongitude(DateTypeUtil.strCastDouble(vo.getLongitude()));
//	        Integer fenceId = null;
//	         try {
//	        	 fenceId = iovFenceService.addFence(iovFenceCreateDto);
//	        	 entrepotStorageService.modifyFenceId(fenceId, vo.getId());
//			} catch (Exception e) {
//				logger.error("车联网添加围栏接口异常：",e);
//			}
//	        
//		}
		
		return null;
	}
	
	/**
	 * key:stockType Integer 类型（1：中转库，2：门店） 
	 * key:shortName String 门店名称
     * key:storeStatus Integer 门店营业状态（null：所有门店，1：门店营业中）
     * key:dealerId Integer 经销商id
     * key:dealerStatus Integer 经销商营业状态（null：所有门店，1：经销商营业中）
     * key:dealerType Integer 经销商类型(null:所有，1:直销，2：分销)
     * key:isShow Integer 删除是否显示(null:所有，0:否，1：是)
	 * @param map
	 * @return
	 * @throws Exception 
	 */
	@Override
	public List<EntrepotStorageBaseVo> getEntrepotOrStore(Map<String, Object> map) throws Exception {
		
		Integer stockType = ObjectCastUtil.castInteger(map.get("stockType"));
		List<EntrepotStorageBaseVo> list = null;
		if(StockCarStockTypeEnum.ENTREPOT_STORAGE.getValue() == stockType) {
			String shortName = ObjectCastUtil.castString(map.get("shortName"));
			List<EntrepotStorageDto> dtos = entrepotStorageService.getByShortName(shortName);
			if(null != dtos && dtos.size() > 0) {
				list = new ArrayList<EntrepotStorageBaseVo>();
				for (EntrepotStorageDto dto : dtos) {
					EntrepotStorageBaseVo vo = new EntrepotStorageBaseVo();
					vo.setShortName(dto.getShortName());
					vo.setStorageId(dto.getId());
					vo.setStockType(stockType);
					list.add(vo);
				}
			}
		}else if(StockCarStockTypeEnum.STORE.getValue() == stockType){
			List<StoreBizDto> dtos = storeBizService.getStoreByShortNameFuzzy(map);
			if(null != dtos && dtos.size() > 0) {
				list = new ArrayList<EntrepotStorageBaseVo>();
				for (StoreBizDto dto : dtos) {
					EntrepotStorageBaseVo vo = new EntrepotStorageBaseVo();
					vo.setShortName(dto.getShortName());
					vo.setStorageId(dto.getStoreId());
					vo.setStockType(stockType);
					list.add(vo);
				}
			}
		}
		return list;
	}
	
	/**
	 * 根据门店或者中转库查 围栏数据信息
	 * @param map
	 * @return
	 */
	@Override
	public List<FenceBaseVo> getEntrepotOrStoreFence(Map<String, Object> map) {
		
		Integer fenceStoreStockType = ObjectCastUtil.castInteger(map.get("stockType"));
		FenceStoreStockTypeEnum  fenceStoreStockEnum= null;
		if(fenceStoreStockType == 2) {
			fenceStoreStockEnum = FenceStoreStockTypeEnum.STORE;
		}else {
			fenceStoreStockEnum = FenceStoreStockTypeEnum.ENTREPOT_STORAGE;
		}
		
		List<Integer> fenceId = fenceStoreStockService.getFenceByStoreId(ObjectCastUtil.castInteger(map.get("id")), fenceStoreStockEnum);
		if( null == fenceId || fenceId.isEmpty() ) {
			return null;
		}
		
		//查询围栏信息
		List<IovFenceDto> fenceList = iovFenceService.getFenceList(fenceId);
		return Convert.toFenceBaseVo(fenceList);
	}

}
